package com.center.growcenterserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.center.growcenterserver.common.R;
import com.center.growcenterserver.mapper.MessageMapper;
import com.center.growcenterserver.model.domain.Message;
import com.center.growcenterserver.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;

@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper,Message> implements MessageService {

    @Autowired
    MessageMapper messageMapper;

    @Override
    public void saveMessage(Message message) {
        try {
            // 设置消息创建时间
            if (message.getCreatedAt() == null) {
                message.setCreatedAt(java.time.LocalDateTime.now());
            }

            // 使用MyBatis-Plus提供的save方法保存消息
            this.save(message);
            log.info("Message saved successfully: {}", message);
        } catch (Exception e) {
            log.error("Failed to save message: {}", e.getMessage(), e);
            // 可以选择抛出异常或进行其他处理
            throw new RuntimeException("Failed to save message", e);
        }
    }

    @Override
    public R getMessage(String courseId) {
        try {
            // 构建查询条件
            QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("to_course_id", courseId); // 假设表中有 to_course_id 字段

            // 执行查询
            List<Message> messages = this.list(queryWrapper);
            return R.success("返回成功",messages);
        } catch (Exception e) {
            // 记录错误日志
            log.error("根据课程ID {} 查询消息失败: {}", courseId, e.getMessage(), e);

            // 返回失败响应
            return R.error("根据课程ID查询消息失败");
        }

    }





}
